package com.wry.wry_test.AQS;

import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wangrongyi
 * @Date: 2024/11/12 9:25
 * @Description:
 */
public class PhaserTest2 {

    private final static Random RANDOM = new Random();


    public static void main(String[] args) {
        final Phaser phaser = new Phaser(3);

        for (int i = 1; i < 3; i++) {
            new Athletes(i, phaser).start();
        }

        // 假设3号运动员受伤了
        new InjuredAthletes(3, phaser).start();
    }

    // 运动员受伤了，需要减少
    static class InjuredAthletes extends Thread {
        private final int no;
        private final Phaser phaser;


        InjuredAthletes(int no, Phaser phaser) {
            this.no = no;
            this.phaser = phaser;

        }

        @Override
        public void run() {
            try {
                sport(no, phaser, " start running.", " end running.");
                sport(no, phaser, " start bicycle.", " end bicycle.");
                System.out.println(no + "号运动员受伤了");
                phaser.arriveAndDeregister();// 动态减少
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Athletes extends Thread {
        private final int no;
        private final Phaser phaser;


        Athletes(int no, Phaser phaser) {
            this.no = no;
            this.phaser = phaser;

        }

        @Override
        public void run() {
            try {
                sport(no, phaser, " start running.", " end running.");
                sport(no, phaser, " start bicycle.", " end bicycle.");
                sport(no, phaser, " start long jump.", " end long jump.");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    private static void sport(int no, Phaser phaser, String x, String y) throws InterruptedException {
        System.out.println(no + x);
        TimeUnit.MILLISECONDS.sleep(RANDOM.nextInt(100));
        System.out.println(no + y);
        phaser.arriveAndAwaitAdvance();
    }
}
